package org.example.mydeom.security;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.mydeom.common.MessageConstant;
import org.example.mydeom.common.RedisConstant;
import org.example.mydeom.util.JwtTokenUtil;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MyLogoutHandler implements LogoutHandler {
    private final RedisTemplate<String, Object> redisTemplate;
    public MyLogoutHandler(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        try {
            // 从请求头中获取token
            String jwt = request.getHeader(JwtTokenUtil.HEADER);
            JwtTokenUtil.validateJwtToken(jwt);
            Long userId = JwtTokenUtil.getUserIdFromJwtToken(jwt);
            // 清除redis中的jwt
            if (userId != null) {
                redisTemplate.delete(RedisConstant.USER_TOKEN + userId);
                log.info("id为{}的用户的token已从Redis中清除", userId);
            }
        } catch (Exception e) {
            log.error("token解析失败:{}",e.getMessage());
            request.setAttribute("error", MessageConstant.TOKEN_PARSING_FAILED);
        }
    }
}
